package cn.pn.project.service;

import cn.pn.project.mapper.base.CityMapper;
import cn.pn.project.pojo.base.City;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;


@RestController
@RequestMapping("/city")
public class CityService {
    @Autowired
    private CityMapper cityMapper;

    /**
     * 查询全部城市并按首字母排序
     * @return 匹配城市集合/null
     */
    @RequestMapping(value = "/mapCity",method = RequestMethod.POST)
    public Map<String,List<City>> mapCity() throws Exception {
        System.out.println("-------------------执行provider中的mapCity方法-------------------");
        //返回数据的总集合
        Map<String,List<City>> allCityMap=null;
        List<City> allCityList = cityMapper.listAllCity();//查询所有城市的数据集合
        System.out.println("-----------城市总数："+allCityList.size());
        //有数据则实例化Map
        if(allCityList!=null||allCityList.size()>0){
            allCityMap=new HashMap<String,List<City>>();
            //外层a-z
            for(char i='a';i<='z';i++) {
                System.out.println("当前匹配字母："+i);
                List<City> subList =  new ArrayList<City>();
                for(int j=0;j<allCityList.size();j++) {//内层总集合元素
                    City city = allCityList.get(j);//获得一个对象
                    //匹配字母
                    System.out.println("当前匹配对象城市字母：" + city.getCityAbbrCode() + "--------获取首字母：" + city.getCityAbbrCode().substring(0, 1));
                    if ((city.getCityAbbrCode().substring(0, 1)).equals(i+"")) {
                        System.out.println("匹配！当前匹配字母："+i+"当前匹配对象字母："+city.getCityAbbrCode());
                        subList.add(city);
                        System.out.println("添加完毕，将进行下一个对象的匹配，当前集合数量："+subList.size());
                    }
                }
                //添加元素
                allCityMap.put(i + "", subList);
            }
        }
        return allCityMap;
    }

    /**
     * 根据城市id查询城市对象
     * @param cityId 城市id
     * @return
     * @throws Exception
     */
    @RequestMapping("/byCityId")
    public City getCityById(@RequestParam("cityId") Integer cityId) throws Exception{
        return cityMapper.getCityById(cityId);
    }

}
